/**
 * @author MFreeman
 */
 	
var MENU_ITEM_ABOUT = 0;
    // set tab-navigation mode and show softkeys
    // (only if we are in the WRT environment)
    if (window.widget) {
        widget.setNavigationEnabled(false);
        menu.showSoftkeys();
	//create about menu
	var aboutMenuItem = new MenuItem("About", MENU_ITEM_ABOUT);
	aboutMenuItem.onSelect = menuItemSelected;
	menu.append(aboutMenuItem);

    }
    

// Callback for when menu items are selected.
function menuItemSelected(id) {
    switch (id) {
       	case MENU_ITEM_ABOUT:
			showAboutView();
			break;
    }
}

//Displays the About view
function showAboutView(){
	$('#accordion').fadeOut("fast",function(){
		if (window.widget) {
        	// set right soft key to "Ok" (returns to main view)
        	menu.setRightSoftkeyLabel("Ok", showMainView);
    	}
		$('#aboutDialog').fadeIn("fast");
	});	
}

function showMainView(){
	$('#aboutDialog').fadeOut("fast",function(){
		if (window.widget) {
        	// set right soft back to "Exit"
        	   menu.setRightSoftkeyLabel("", null);
    	}
		$('#accordion').fadeIn("fast");
		$("newVersion").html('');
	});	
}


function checkRegexp(o,regexp,n) {

	if ( !( regexp.test( o.val() ) ) ) {
		o.addClass('ui-state-error');
		$("#emailError").html(n);
		return false;
	} else {
		return true;
	}

}
//function to add Evernote inbound email to your contacts list
function addContact(ev_email){
	
	try{ 
	    var contact = com.nokia.device.load("", "com.nokia.device.contacts", ""); 
	    var contactEntry = { 
	     name:{ 
	      last: "Evernote E-Mail" 
	     }, 
		 address: {
            email: ev_email,
            url: 'http://www.evernote.com/mobile'
			},
	     company: {
             name: 'Evernote'
             
            } 
	    }; 
	    contact.addContact(contactEntry);
		
		$("<div>Contact successfully added!</div>").dialog({
			bgiframe: false,
			autoOpen: true,
			show: 'drop',
			hide: 'drop',
			modal: true,
			title: "Contact Added",
			buttons: {
				'OK': function() {
				$(this).dialog('close');
					}
				}
		});
		
	
	 } 
	 catch(e){ 
	    var error = e.toString(); 
	    $();
	 } 
 }	
	
function setupEmail(){
		var bodyTxt = "?body=Sent by my Evernote Mobile";
		var prefLength = 0;
		try {
		 prefLength = widget.preferenceForKey("everEmail").length;
	} catch (e) {
		
	}
		if (prefLength < 5) {
 
		//TODO REMOVE BEFORE DEPLOYING
		try {
			$.get(
				"http://www.evernote.com/mobile/JSMobile.action?accountInfo=",
				function(data){
  					var obj = $.evalJSON(data);
						if (window.widget) {
							widget.setPreferenceForKey(obj.accountInfo.incomingEmailAddress, "everEmail");			}
						
						prefLength = obj.accountInfo.incomingEmailAddress.length;						
						
						if (prefLength < 5) {
							$(".addEmail").text('Evernote e-mail setup');
							$(".mailSetupYes").css("display","none");
							
						}
						else {
							//Evernote e-Mail is setup
							$(".addEmail").text('Change Evernote e-mail');
							$(".mailSetupYes").css("display","");
							$("#email").val(widget.preferenceForKey("everEmail"));						
							$(".sendNow").attr("href","mailto:" + $("#email").val() + bodyTxt);
							
						}
						
					
  				},
				"text"
			);
			} catch (e) {
			console.log("error in get: "+ e.toString());
						}

			
		}
		else {
				//Evernote e-Mail is setup
				$(".addEmail").text('Change Evernote e-mail');
				$(".mailSetupYes").css("display","");
				$("#email").val(widget.preferenceForKey("everEmail"));	
				$(".sendNow").attr("href","mailto:" + $("#email").val() + bodyTxt);
				
		}

}


jQuery('document').ready(function(){
	welcome();
	$('#aboutDialog').hide();

//setup accordion
	$("#accordion").accordion({ fillSpace: false,  autoHeight:false, header: 'h3', icons: { 'header': 'ui-icon-circle-arrow-e', 'headerSelected': 'ui-icon-circle-arrow-s' }  });
	
	$("#everFrame").attr("src","http://www.evernote.com/mobile/MobileSetup.action?noRedirect=true");
	
//setup email dialog
	var email=	$("#email");
	$("#dialog").dialog({
			bgiframe: false,
			autoOpen: false,
			height: 300,
			show: 'drop',
			hide: 'drop',
			modal: false,
			title: "Evernote Incoming email address",
			buttons: {
				'Store your e-mail address': function() {
					var bValid = true;
					email.removeClass('ui-state-error');
					bValid = bValid && checkRegexp(email,/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i,"eg. ui@jquery.com");
					if (bValid) {
					 if (window.widget) {
					 	widget.setPreferenceForKey(email.val(), "everEmail");
					 }
					 setupEmail();
						$(this).dialog('close');
					}
				},
				Cancel: function() {
					$(this).dialog('close');
				}
			},
			open: function() {	
				if (window.widget) {
						$('#email').val(widget.preferenceForKey("everEmail"));
				}			
	
			},
			close: function() {
				email.removeClass('ui-state-error');
			}
		});
		
	$('.addEmail').click(function() {
		$('#dialog').dialog('open');
	});
	
	$('.addContact').click(function() {
			addContact($("#email").val());
	});
	
	$('.updateCheck').click(function() {
		checkUpdates();
	});
	
	$('.qNote').click(function() {
		setupEmail();
	});
	
	$('.emailWrap a').hover(
			function(){ 
				$(this).addClass("ui-state-hover"); 
			},
			function(){ 
				$(this).removeClass("ui-state-hover"); 
			}
		).mousedown(function(){
			$(this).addClass("ui-state-active"); 
		})
		.mouseup(function(){
				$(this).removeClass("ui-state-active");
		});
		
//	var ev_email = setupEmail();	

//version # setup				
	if (window.widget) {
		widget.setPreferenceForKey("1.01", "version");
		$('.oldVersion').text(widget.preferenceForKey("version"));
	}	
	$(".loading").fadeOut("slow");

	});

function checkUpdates(){
	var span = $(".newVersion");
	span.text("Checking for updates...");
			try {
		//	netscape.security.PrivilegeManager.enablePrivilege("UniversalBrowserRead"); 
		} catch (e) {
		}

	
	try {
			$.get(
				"http://evernote-s60.googlecode.com/files/current_version.txt",
				function(data){
  					var obj = $.evalJSON(data);
						if (window.widget) {
						var curVer = widget.preferenceForKey("version");
						var newVer = obj.currentVersion;
							if (curVer < newVer){
								span.html('<strong>New Version Available</strong><BR/><BR/> <a class="updateButton ui-corner-all ui-state-default" href="http://evernote-s60.googlecode.com/files/SymbianNote.wgz">Click here to download</a>');
							}else{
								span.html("You have the latest version.");
							}
						}
					
  				},
				"text"
			);
			} catch (e) {
				span.text("There was a problem. Try again later.");
						}
						
		
}

function welcome(){
	if (window.widget){
	
		if(widget.preferenceForKey("firstTime") == "true"){
			return;
		} 
		else{
		widget.setPreferenceForKey("true","firstTime");
			$("<div>,<p>This is your first time using this widget.</p><p> Welcome and enjoy!</p></div>").dialog({
			bgiframe: false,
			autoOpen: true,
			show: 'drop',
			hide: 'drop',
			modal: false,
			title: "Welcome to Evernote for Symbian",
			buttons: {
				'OK': function() {
				$(this).dialog('close');
					}
				}
		});
		}
	
	
	}
}